const { Controller } = require('egg');


/**
 * 定义公共的操作方法
*/
class ComtrollerService extends Controller {
  constructor() {
    super(...arguments);

    /**
		 * @abstract 操作的数据库表
		*/
    this.tableName = '';
    /**
		 * @abstract 定义下载的表头
		*/
    this.downloadExcelHeader = [];
  }

  /**
   * 获取报名数据
  */
  async index() {
    const { ctx, tableName } = this;
    const { pageSize = 10, pageNum = 1, name, phone } = ctx.query;
    const whereOpt = {};
    if (name) {
      whereOpt.name = name;
    }
    if (phone) {
      whereOpt.phone = phone;
    }
    const result = await ctx.service.car.carService.getBMList({
      pageSize,
      pageNum,
      table: tableName,
      options: {
        where: whereOpt, // WHERE 条件
      },
    });
    ctx.body = {
      code: 200,
      message: 'success',
      data: result,
    };
  }

  /**
  * 更新报名数据信息
 */
  async update() {
    const { ctx, tableName } = this;
    const { id } = ctx.request.body;
    if (!id) {
      ctx.body = {
        code: 400,
        message: '请输入需要更新的主键id',
      };
      return false;
    }
    const result = await ctx.service.car.carService.updateBMBy({
      table: tableName,
      row: ctx.request.body,
    });
    // 判断是否更新成功
    if (result.affectedRows === 1) {
      ctx.body = {
        code: 200,
        message: 'success',
      };
    } else {
      ctx.body = {
        code: 500,
        message: '更新失败',
      };
    }
  }


  /**
   * 删除报名数据
  */
  async destroy() {
    const { ctx, tableName } = this;
    const { id } = ctx.params;
    if (!id) {
      ctx.body = {
        code: 400,
        message: '主键id不存在',
      };
      return false;
    }
    const result = await ctx.service.car.carService.deleteBMBy({
      table: tableName,
      id,
    });
    // 判断是否删除成功
    if (result.affectedRows === 1) {
      ctx.body = {
        code: 200,
        message: 'success',
      };
    } else {
      ctx.body = {
        code: 500,
        message: '删除失败',
      };
    }
  }


  /**
   * 下载数据库文件
  */
  async download() {
    const { ctx, tableName, downloadExcelHeader } = this;
    const { pageSize, pageNum, name, phone } = ctx.query;
    const options = {
      pageSize,
      pageNum,
      where: {},
    };
    if (name) {
      options.where.name = name;
    }
    if (phone) {
      options.where.phone = phone;
    }
    await ctx.service.car.carService.exportAll(tableName, downloadExcelHeader, options);
  }
}

module.exports = ComtrollerService;
